<template>

    <div style="text-align: left">
      <el-steps :active="currentStep" finish-status="success" :align-center="true">
        <el-step title="检查设备"></el-step>
        <el-step title="同意条款"></el-step>
      </el-steps>
      <div class="claim-task-content-container">
        <div v-if="currentStep === 0">
          <div class="border-block" style="cursor: pointer">
            <div @click="deviceRequirementVisible = !deviceRequirementVisible" class="border-block-title">
              任务设备需求
              <i :class="deviceRequirementVisible ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
            </div>
            <DeviceRequirementsView v-if="deviceRequirementVisible" :value="deviceRequirement"></DeviceRequirementsView>
          </div>

          <div class="border-block">
            <div class="border-block-title">我的设备</div>
            <div style="margin-bottom: 10px"><strong>如果您的设备列表中目前没有符合要求的设备，或者现有设备不能正常运行，可以点击添加按钮来添加符合要求的新设备。<span style="color: dodgerblue">在执行任务的过程中如果删除或者修改设备导致没有任何符合任务要求的设备，从而导致无法完成任务，责需要自行承担后果。</span></strong></div>
            <div class="device-list">
              <device-card-view v-for="device in myDevicesList" :key="device.id" :value="device">
                <template #header>
                  <div style="text-align: right">
                    <el-checkbox @change="handleCheckBoxChange($event)"></el-checkbox>
                  </div>
                </template>
              </device-card-view>
              <add-device-card
                  :add-device="addDevice"
                  :init-device="initDevice"
                  @saved="handleSaved()"
                  @error="handleError($event)">
              </add-device-card>
            </div>
          </div>
        </div>
        <div v-else-if="currentStep === 1">
          <div class="border-block">
            <div class="border-block-title">注意事项：</div>
            <div>
              <strong style="color: dodgerblue">
                一旦接受任务后不可反悔，逾期未完成任务将被视为失信行为。
              </strong>
            </div>
          </div>
        </div>
      </div>
      <div class="btn-container">
        <el-button :style="{visibility: currentStep !== 0 ? 'visible' : 'hidden'}" type="text"
                   @click="currentStep = (currentStep + 1) % 2">
          <i class="el-icon-arrow-left"></i>
          上一步
        </el-button>
        <el-button v-if="currentStep < 1" type="text" @click="currentStep = (currentStep + 1) % 2" :disabled="availableDeviceNum === 0">
          {{ availableDeviceNum === 0 ? "请先确保至少有一个设备可以正常使用！" : "下一步" }}
          <i v-if="availableDeviceNum !== 0" class="el-icon-arrow-right"></i>
        </el-button>
        <el-button v-else type="primary" @click="handleGetTask()">
          同意条款并接受任务
        </el-button>
      </div>
    </div>

</template>

<script>
import DeviceRequirementsView from "@/components/new/device-requirements-card/DeviceRequirementsView";
import MyDeviceList from "@/views/new/device-management/MyDeviceList";
import DeviceCardView from "@/components/new/device-card/DeviceCardView";
import AddDeviceCard from "@/components/new/device-card/AddDeviceCard";
import {claimTask, postUserDevice} from "@/api/worker";
import {getTaskDeviceRequirements, getTaskWorkerDevices} from "@/api/task";

export default {
  name: "ClaimTask",
  components: {AddDeviceCard, DeviceCardView, MyDeviceList, DeviceRequirementsView},
  props: {
    taskId: {
      default: -1
    }
  },
  data() {
    return {
      currentStep: 0,
      deviceRequirement: {
        osList: [],
        minRam: 1,
        maxRam: 1,
        processorArchitectureList: []
      },
      deviceRequirementVisible: false,
      myDevicesList: [],
      availableDeviceNum: 0
    }
  },
  methods: {
    initAll(){
      this.loadDeviceRequirement();
      this.loadAvailableDevice().then(() => {
        if(this.myDevicesList.length === 0){
          this.deviceRequirementVisible = true;
        }
      });
    },
    handleCheckBoxChange(checked){
      if(checked){
        this.availableDeviceNum++;
      }else{
        this.availableDeviceNum--;
      }
    },
    handleError(err) {
      this.$message.error(err.message);
    },
    handleSaved() {
      this.loadAvailableDevice();
    },
    addDevice(device) {
      return new Promise((resolve, reject) => {
        if (this.validDevice(device)) {
          resolve(postUserDevice(sessionStorage.getItem('userid'), device));
        } else {
          reject(new Error('设备不符合任务要求！'));
        }
      })
    },
    validDevice(device) {
      return this.deviceRequirement.osList.indexOf(device.os) !== -1
          && this.deviceRequirement.processorArchitectureList.indexOf(device.processorArchitecture) !== -1
          && device.ram <= this.deviceRequirement.maxRam
          && device.ram >= this.deviceRequirement.minRam;
    },
    loadAvailableDevice() {
      return getTaskWorkerDevices(this.taskId, sessionStorage.getItem('userid'))
          .then(res => {
            if (res.code === 200) {
              this.myDevicesList = res.data;
            } else {
              throw new Error(res.msg);
            }
          }).catch(err => {
            this.$message.error(err.message);
          })
    },
    loadDeviceRequirement() {
      return getTaskDeviceRequirements(this.taskId)
          .then(res => {
            if (res.code === 200) {
              this.deviceRequirement = res.data;
            } else {
              throw new Error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err.message);
          });
    },
    handleGetTask() {
      claimTask({
        workerid: sessionStorage.getItem('userid'),
        taskid: this.taskId
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('领取成功！');
          this.$emit('claimed')
        } else {
          throw new Error(res.msg);
        }
      }).catch(err => {{
        this.$emit('error', err);
      }});
    },
  },
/*  mounted() {
    this.initAll();
  },*/
  computed: {
    initDevice() {
      return {
        id: -1,
        os: this.deviceRequirement.osList[0],
        ram: this.deviceRequirement.minRam,
        processorArchitecture: this.deviceRequirement.processorArchitectureList[0]
      }
    }
  }
}
</script>

<style scoped>
.border-block {
  border-radius: 5px;
  border: 1px solid lightgrey;
  margin-top: 50px;
  padding: 10px 15px;
}

.border-block-title {
  position: relative;
  top: -18px;
  left: 70px;
  font-size: 16px;
  line-height: 16px;
  width: 140px;
  background-color: white;
  text-align: center;
}

.claim-task-content-container {
  height: 450px;
  overflow-y: auto;
}

.btn-container {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.device-list {
  display: grid;
  grid-template-columns: repeat(
      auto-fill,
      minmax(300px, 1fr)
    );
  grid-gap: 20px;
}

.add-btn-container {
  cursor: pointer;
  height: 260px;
  display: flex;
  justify-content: center;
}
</style>
